﻿/*
--------------------------------------
File: CropLicenseplate.cs
Project: Themaopdracht 7
Author: Thierry Gerritse

Description:
A algorithm which crops the image around the license plate, returns cropped original image,
--------------------------------------
*/
/// <summary>
/// Crops a license plaate based on a black and white mask
/// </summary>
/// <param name="blackWhiteSourceImage">The image containing ONLY the license plate in white.</param>
/// <param name="colorSourceImage">The original unaltered image to crop</param>
/// <returns>The cropped license plate in color</returns>
///

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace THO7_Team8
{
	internal class CropLicenseplateColoured
	{
		private static int BLACK = -16777216;

		public CropLicenseplateColoured(String name)
		{
		}

		public System.Drawing.Bitmap CropLicensePlateFromOriginal(System.Drawing.Bitmap blackWhiteSourceImage, System.Drawing.Bitmap colorSourceImage)
		{
			Bitmap colorImage = new Bitmap(colorSourceImage);
			Bitmap blackWhiteImage = new Bitmap(blackWhiteSourceImage);

			int[] blackWhiteSourceArray = MyImage.BmpToArray(blackWhiteImage);
			//Console.WriteLine(blackWhiteSourceImage.PixelFormat.ToString());
			int[] colorSourceArray = MyImage.BmpToArray(colorImage);
			int width = blackWhiteSourceImage.Width;

			//Finds the dimensions for the new bitmap
			int firstX = width, firstY = 0, lastX = 0, lastY = 0;

			for(int i = 0; i < blackWhiteSourceArray.Length; i++)
			{
				if(blackWhiteSourceArray[i] != BLACK)
				{
					//The first Y is the first non black pixel
					if(firstY == 0)
					{
						firstY = i / width;
					}
					//The first X is the most left non black pixel
					if(firstX > (i % width))
					{
						firstX = i % width;
					}
					//The last X pixel is the most right non black pixel
					if((i % width) > (lastX % width))
					{
						lastX = i % width;
					}
					//The last Y pixel is the last right non pixel
					lastY = i / width;
				}
			}

			if(lastX != 0 && lastY != 0 && firstY != 0)
			{
				//Creates the new bitmap with the dimensions and the new array
				Bitmap croppedBitmap = new Bitmap(lastX - firstX, lastY - firstY);

				int[] croppedArray = MyImage.BmpToArray(croppedBitmap);

				//Crops the image
				int counter = 0;
				for(int y = firstY; y < lastY; y++)
				{
					for(int x = firstX; x < lastX; x++)
					{
						croppedArray[counter] = colorSourceArray[y * width + x];
						counter++;
					}
				}

				croppedBitmap = MyImage.ArrayToBmp(croppedArray, croppedBitmap);
				return croppedBitmap;
			}
			else
			{
				return null;
			}
		}
	}
}